﻿//https://leetcode.cn/problems/add-two-numbers/
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* cur1 = l1;
        ListNode* cur2 = l2;
        ListNode* newHead = new ListNode;
        ListNode* pos = newHead;
        int tmp = 0;
        while (cur1 && cur2)
        {
            tmp = cur1->val + cur2->val + tmp;
            ListNode* newNode = new ListNode;
            newNode->val = tmp % 10;
            pos->next = newNode;

            tmp = tmp / 10;
            pos = newNode;
            cur1 = cur1->next;
            cur2 = cur2->next;
        }
        while (cur1)
        {
            tmp = cur1->val + tmp;
            ListNode* newNode = new ListNode;
            newNode->val = tmp % 10;
            pos->next = newNode;

            pos = newNode;
            tmp = tmp / 10;
            cur1 = cur1->next;
        }
        while (cur2)
        {
            tmp = cur2->val + tmp;
            ListNode* newNode = new ListNode;
            newNode->val = tmp % 10;
            pos->next = newNode;

            pos = newNode;
            tmp = tmp / 10;
            cur2 = cur2->next;
        }
        while (tmp)
        {
            ListNode* newNode = new ListNode;
            newNode->val = tmp % 10;
            pos->next = newNode;

            pos = newNode;
            tmp = tmp / 10;
        }
        return newHead->next;
    }
};

//答案
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
    public :
    ListNode * addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        ListNode* cur1 = l1, * cur2 = l2;
        ListNode* newhead = new ListNode(0); // 创建⼀个虚拟头结点，记录最终结果
        ListNode* prev = newhead; // 尾指针
        int t = 0; // 记录进位
        while (cur1 || cur2 || t)
        {
            // 先加上第⼀个链表
            if (cur1)
            {
                t += cur1->val;
                cur1 = cur1->next;
            } /
                / 加上第⼆个链表
                if (cur2)
                {
                    t += cur2->val;
                    cur2 = cur2->next;
                } p
                    rev->next = new ListNode(t % 10);
                prev = prev->next;
                t /= 10;
        } p
            rev = newhead->next;
        delete newhead;
        return prev;
    }
};